package com.backend.mzyf.interceptor;

import com.backend.mzyf.Utils.ResourceUtil;
import com.backend.mzyf.entity.ActiveUser;
import com.backend.mzyf.entity.SysPermission;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

public class PermissionInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String url = httpServletRequest.getRequestURI();

        List<String> anonymousUrls = new ResourceUtil().getUrls("anonymousUrl");

        //判断访问的地址是否为匿名访问地址
        for (String anonymousUrl : anonymousUrls) {
            if (url.indexOf(anonymousUrl) >= 0) {
                return true;
            }

        }


        List<String> commonUrls = new ResourceUtil().getUrls("commonUrl");

        //判断访问的地址是否为匿名访问地址
        for (String commonUrl : commonUrls) {
            if (url.indexOf(commonUrl) >= 0) {
                return true;
            }

        }

        HttpSession session = httpServletRequest.getSession();
        //判断session中是否有值，如果有值就放行
        ActiveUser activeUser = (ActiveUser) session.getAttribute("activeUser");
        //获取权限url
        List<SysPermission> sysPermissions = activeUser.getPermissions();

        for (SysPermission sysPermission : sysPermissions) {
            if (url.indexOf(sysPermission.getUrl()) >= 0) {
                return true;
            }
        }

        httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/forbidden");

        return false;
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("HandlerInterceptor2...postHandle1");
    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("HandlerInterceptor2...afterCompletion1");
    }
}
